package httpService

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/labstack/echo/v4"
	"github.com/smallnest/rpcx/client"
	"github.com/smallnest/rpcx/protocol"
	"pm/db"
	"pm/model"
	"pm/rpc"
	"pm/util"
	"strconv"
	"strings"
)

func PackagePubic(c echo.Context)error{

	//获取参数
	idParam := c.FormValue("id")
	id,_ := strconv.Atoi(idParam)
	var PackageData model.PackageHistory
	err := db.NewDb().Model(&model.PackageHistory{}).Where("ID =?", id).Take(&PackageData).Error
	if err != nil {
		return c.JSON(200, map[string]interface{}{
			"status": 1,
			"msg":"包不存在",
		})
	}


	if !util.FileExists(PackageData.FilePath) {
		return c.JSON(200, map[string]interface{}{
			"status": 1,
			"msg":"版本包文件不存在",
		})
	}

	doPackageDispense(PackageData.Name, PackageData.Version, PackageData.FilePath)

	db.NewDb().Model(&model.PackageHistory{}).Where("name = ?", PackageData.Name).Update("current", 0)
	PackageData.Status = 2
	PackageData.Current = 1
	db.NewDb().Model(&model.PackageHistory{}).Where("ID = ?", PackageData.ID).Updates(PackageData)
	return c.JSON(200, map[string]interface{}{
		"status": 0,
		"msg":"发布成功",
	})
}

func doPackageDispense(name, version, packagePath string) error {
	var packageConfig model.Package
	err := db.NewDb().Where("name = ?", name).Take(&packageConfig).Error
	if err != nil{
		return err
	}
	clientList := make([]model.Client, 0)
	if packageConfig.Servers != ""{
		for _,s := range strings.Split(packageConfig.Servers, ","){
				clientList = append(clientList, model.Client{
					Host: s,
				})
		}
	}else{
		db.NewDb().Find(&clientList)
	}

	for _, item := range clientList {
			d, _ := client.NewPeer2PeerDiscovery(item.Host+":"+strconv.Itoa(rpc.Port), "")
			opt := client.DefaultOption
			opt.SerializeType = protocol.JSON
			xclient := client.NewXClient(rpc.ServerName, client.Failtry, client.RandomSelect, d, opt)
			var reply rpc.DataOutput
			params := map[string]interface{}{
				"name":         name,
				"version":      version,
				"path": packagePath,
				"hash":util.GetFilehash(packagePath),
				"public_path":packageConfig.Path,
				"type":packageConfig.Type,
				"args":packageConfig.Args,
			}
			fmt.Println(params)
			paramsStr, _ := json.Marshal(params)
			xclient.Call(context.Background(), "package.on.update", string(paramsStr), &reply)
	}
	return nil
}